from django.views.decorators.csrf import csrf_exempt
from rest_framework.decorators import api_view

from user.service import UserService
from utils.exception_handler import my_exception_handler
from utils.authorize import authorize
from utils.request import params
from utils.response import success
from utils.tools import get_now


@csrf_exempt
@api_view(["POST"])
@my_exception_handler
@params(required=["username", "password"])
def login(request):
	result = UserService().user_login(**request.params)
	request.session["user"] = result
	request.session.save()
	return success(result, "登录成功")

@csrf_exempt
@api_view(["GET"])
@my_exception_handler
@authorize
def login_status(request):
	return success(request.session["user"], "账号已登录")

@csrf_exempt
@api_view(["POST"])
@my_exception_handler
@params(required=["username", "password"], optional=["nickname"])
def register(request):
	result = UserService().user_register(**request.params)
	return success(result, "注册成功")

@csrf_exempt
@api_view(["GET"])
@my_exception_handler
@authorize
def logout(request):
	request.session.delete()
	return success(msg="退出登录成功")

@csrf_exempt
@api_view(["GET"])
@my_exception_handler
def user_info(request, uid):
	result = UserService().get_user(uid)
	return success(result, "获取成功")

@csrf_exempt
@api_view(["PUT","POST"])
@my_exception_handler
@authorize
@params(required=["avatar"])
def user_avatar(request):
	uid = request.session["user"]["uid"]
	result = UserService().user_avatar(uid, **request.params)
	user_info = request.session["user"]
	user_info["avatar"] = result
	request.session.update({"user": user_info})
	return success({"newAvatar": result}, "修改头像成功")


